<template>
  <div>
    <ElRow style="margin-bottom: 16px;">
      <el-button type="primary" @click="addRole" v-if="hasPerms('role:create')">新增</el-button>
    </ElRow>
    <ReTable :data="roleList" :columns="columns" :pagination="pagination" @size-change="handleSizeChange"
      @current-change="handleCurrentChange">
      <template #action="{ row }">
        <ElRow justify="center" align="middle">
          <ElCol :span="6" v-if="hasPerms('role:edit')">
            <ElButton link type="primary" @click="editRole(row)">
              编辑
            </ElButton>
          </ElCol>
          <ElCol :span="6" v-if="hasPerms('role:status')">
            <ElSwitch v-model="row.status" inline-prompt active-text="启用" inactive-text="禁用" :active-value="1"
              :inactive-value="0" @change="changeStatus(row)">
            </ElSwitch>
          </ElCol>
        </ElRow>
      </template>
    </ReTable>
    <ElDialog v-model="dialogVisible" :title="dialogTitle" width="520" destroy-on-close>
      <ElForm ref="ruleFormRef" :model="formData" :rules="rules" label-width="auto" class="demo-ruleForm" status-icon>
        <ElFormItem label="角色名" prop="roleName">
          <ElInput v-model="formData.roleName" autocomplete="off" placeholder="请输入角色名"
            :disabled="dialogTitle === '编辑角色'" />
        </ElFormItem>
        <ElFormItem label="权限管理" prop="permissions" v-if="dialogTitle === '编辑角色'">
          <el-checkbox-group v-model="formData.permissions">
            <el-checkbox v-for="item in allPermissionList" :key="item.code" :value="item.code"
              :label="item.description"></el-checkbox>
          </el-checkbox-group>
        </ElFormItem>
        <ElRow justify="end">
          <ElCol :span="4">
            <ElButton @click="dialogVisible = false">取消</ElButton>
          </ElCol>
          <ElCol :span="4">
            <ElButton type="primary" @click="submitForm(ruleFormRef)">确定</ElButton>
          </ElCol>
        </ElRow>
      </ElForm>
    </ElDialog>
  </div>
</template>

<script setup lang="ts">
import { addRoleSubmit, queryRoleList, updateRoleStatus, getRolePermission, getAllPermissionList, setRolePermission } from '@/api/role';
import { onMounted } from 'vue';
import { ref } from 'vue';
import { ReTable } from '@/components/ReTable'
import { ElMessage } from 'element-plus';
import { permission } from 'process';
import { hasPerms } from '@/utils/auth';

defineOptions({
  // name 作为一种规范最好必须写上并且和路由的name保持一致
  name: "RoleManage"
});

// 角色列表数据
const roleList = ref([])
// 角色新增弹窗
const dialogVisible = ref(false)
// 弹窗标题
const dialogTitle = ref('新增角色')
// 表单引用
const ruleFormRef = ref()
// 表单数据
const formData = ref({
  id: '',
  roleName: '',
  permissions: []
})
// 所有权限
const allPermissionList = ref([])
// 分页数据
const pagination = ref({
  pageNum: 1,
  pageSize: 10,
  total: 0
})
const rules = {
  roleName: [
    { required: true, message: '请输入角色名称', trigger: 'blur' },
  ],
  permissions: [
    { required: true, message: '请选择权限', trigger: 'change' },
  ]
}
const columns = [
  {
    label: '角色ID',
    prop: 'id'
  },
  {
    label: '角色名称',
    prop: 'roleName'
  },
  {
    label: '创建时间',
    prop: 'gmtCreate'
  },
  {
    label: '创建人',
    prop: 'createBy'
  },
  {
    label: '操作',
    prop: 'action',
    slotName: 'action'
  }
]

// 查询角色列表
const getRoleList = () => {
  queryRoleList({
    pageNum: pagination.value.pageNum,
    pageSize: pagination.value.pageSize
  }).then(res => {
    roleList.value = res.data.records
    pagination.value.total = res.data.total
  })
}

// 新增角色
const addRole = () => {
  dialogTitle.value = '新增角色'
  dialogVisible.value = true
}

// 编辑角色
const editRole = async (row: any) => {
  dialogTitle.value = '编辑角色'
  formData.value.roleName = row.roleName
  formData.value.id = row.id
  const res = await getRolePermission(row.id)
  formData.value.permissions = res.data
  dialogVisible.value = true
}

// 提交表单
const submitForm = (formEl: any) => {
  if (!formEl) return
  formEl.validate((valid: boolean) => {
    if (valid) {
      if (dialogTitle.value === '新增角色') {
        addRoleSubmit(formData.value).then(res => {
          ElMessage.success('操作成功')
          dialogVisible.value = false
          getRoleList()
        })
      } else {
        setRolePermission({
          roleId: formData.value.id,
          permissions: formData.value.permissions
        }).then(res => {
          ElMessage.success('操作成功')
          dialogVisible.value = false
          getRoleList()
        })
      }
    } else {
      console.log('error submit!')
      return false
    }
  })
}

const handleSizeChange = (val: number) => {
  pagination.value.pageSize = val
  getRoleList()
}

const handleCurrentChange = (val: number) => {
  pagination.value.pageNum = val
  getRoleList()
}

// 改变角色状态
const changeStatus = async (row: any) => {
  const res = await updateRoleStatus({
    roleId: row.id,
    status: row.status
  })
  if (res.code === 200) {
    ElMessage.success('操作成功')
    getRoleList()
  }
}

// 查询所有角色权限列表
const queryAllPermissionList = async () => {
  try {
    const res = await getAllPermissionList()
    if (res.code === 200) {
      allPermissionList.value = res.data
    }
  } catch (error) {
    ElMessage.error('获取权限列表失败')
  }
}

// 初始化
onMounted(() => {
  getRoleList()
  queryAllPermissionList()
})

</script>